<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button plain type="primary" @click="addRoleDialog = true">添加角色</el-button>
          <el-table :data="rolelist" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                  <!-- 一级 -->
                  <el-col :span="5">
                    <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                      <!-- 二级 -->
                      <el-col :span="6">  
                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <!-- 三级 -->
                      <el-col :span="18">
                        <el-tag type="warning" closable v-for="(item3,i3) in item2.children" :key="item3.id"
                          @close="removeRightById(scope.row,item3.id)">
                          {{item3.authName}}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <!-- <pre>{{scope.row}}</pre> -->
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="300px">
              <template slot-scope="scope">
                <el-button plain size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row.id)">
                  编辑
                </el-button>
                <el-button plain size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">
                  删除
                </el-button>
                <el-button plain size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">
                  分配权限
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialog" width="50%" @close="setRightDialogClosed">
      <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加用户" :visible.sync="addRoleDialog" @close="addClosed" width="50%">
      <el-form ref="addFormRef" :model="addForm" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑用户" :visible.sync="editRoleDialog" @close="editRoleDialog=false" width="50%">
      <el-form ref="editFormRef" :model="editForm" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        rolelist: [],
        addRoleDialog: false,
        editRoleDialog: false,
        setRightDialog: false,
        rightslist:[],
        treeProps:{
          label: 'authName',
          children: 'children'
        },
        defKeys: [],
        addForm: {
          roleName: '',
          roleDesc: '',
          roleId: ''
        },
        editForm: {},
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      async getRolesList() {
        const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.rolelist = res.data
      },
      async addRole() {
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加成功')
        this.addRoleDialog = false
        this.getRolesList()
      },
      addClosed() {
        this.$refs.addFormRef.resetFields()
      },
      async edit(id) {
        const { data: res } = await this.$http.get('roles/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('查询用户失败')
        }
        this.editForm = res.data
        // alert(this.editForm.roleId)
        this.editRoleDialog = true
      },
      async editRole() {
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        this.$message.success('更新用户信息成功')
        this.getRolesList()
        this.editRoleDialog = false
      },
      async deleteRole(id) {
        const confirmResult = await this.$confirm(
          '此操作将永久删除该, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).catch((err) => {
          return err
        })
        // 如果用户确认删除，则返回值为字符串 confirm
        // 如果用户取消了删除，则返回值为字符串 cancel
        console.log(confirmResult)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除角色失败！')
        }
        this.$message.success('删除角色成功！')
        this.getRolesList()
      },
      //删除权限
      async removeRightById(role,rightId){
        const confirmResult = await
        this.$confirm('是否删除此角色','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult !== 'confirm') {
          return this.$message.info('取消了删除！')
        }
        const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status !==200){
          return this.$message.error('删除权限失败')
        }
        role.children = res.data 
      },
      //树形分配权限对话框
      async showSetRightDialog(role) {
        this.roleId = role.id
        const {data : res} = await this.$http.get('rights/tree')
        if(res.meta.status !== 200){
          return this.$message.error('获取权限数据失败')
        }
        this.rightslist = res.data;
        console.log(this.rightslist)
        this.getLeafKeys(role,this.defKeys)
        this.setRightDialog = true;
      },
      //递归，获取角色下所有三级权限的id
      getLeafKeys(node,arr) {
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item =>
          this.getLeafKeys(item,arr))
      },
      //监听分配权限对话框的关闭事件
      setRightDialogClosed(){
        this.defKeys = []
      },
      async allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status !== 200){
          return this.$message.error('分配权限失败！')
        }
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.setRightDialog = false
      }
    },
  }
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>